import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers.Authorization = `${getToken()}`
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    // 判断是不是blob
    // if (response.data instanceof Blob) {
    //   return response.data // 返回了Blob对象
    // }
    return response.data
  },
  error => {
    // token失效
    if (error.response.status === 401) {
      Message.warning('尊敬的用户,当前登录状态已过期!')
      store.commit('user/SET_TOKEN', '')
      // 2. 跳转登录
      router.push('/login')
    } else {
      Message(error.response.data.msg)
    }
    return Promise.reject(error)
  }
)

export default service
